﻿using System;
using System.Net.Http;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;
using System.Windows.Threading;

namespace Infrastructure
{
    public class Utilities
    {
        /// <summary>
        /// Controller调用WebApiController方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="uri"></param>
        /// <param name="apiurl"></param>
        /// <returns></returns>
        public static T InvokeWebApi<T>(Uri uri, string apiurl)
        {
            T result = default(T);
            using (var client = new System.Net.Http.HttpClient())
            {
                client.BaseAddress = uri;
                result = client.GetAsync(apiurl).Result.Content.ReadAsAsync<T>().Result;
                return result;
            }
        }

        public static void Invoke(Action action)
        {
            Dispatcher dispatchObject = Application.Current.Dispatcher;
            if (dispatchObject == null || dispatchObject.CheckAccess())
            {
                action();
            }
            else
            {
                dispatchObject.BeginInvoke(action);
            }
        }

        public static byte[] SerializeObject(object pObj)
        {
            if (pObj == null)
                return null;
            System.IO.MemoryStream _memory = new System.IO.MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(_memory, pObj);
            _memory.Position = 0;
            byte[] read = new byte[_memory.Length];
            _memory.Read(read, 0, read.Length);
            _memory.Close();
            return read;
        }

        public static object DeserializeObject(byte[] pBytes)
        {
            object _newOjb = null;
            if (pBytes == null)
                return _newOjb;
            System.IO.MemoryStream _memory = new System.IO.MemoryStream(pBytes);
            _memory.Position = 0;
            BinaryFormatter formatter = new BinaryFormatter();
            _newOjb = formatter.Deserialize(_memory);
            _memory.Close();
            return _newOjb;
        }
    }
}
